import {
  View,
  Picker,
  Text,
  Textarea,
  Input,
  ScrollView,
} from "@tarojs/components";
import { Component, ReactNode } from "react";
import Taro from "@tarojs/taro";
import {
  AtInput,
  AtForm,
  AtButton,
  AtImagePicker,
  AtList,
  AtTextarea,
  AtListItem,
  AtNavBar,
} from "taro-ui";
import Req, { BASE_URL } from "../../utils/request";
import "./index.scss";
import ProjectSelect from "../../components/ProjectSelect";
import { isEmpty, uploadImgConvertUrl, debounce } from "../../utils/kit";
import { getInfo } from "../../utils/auth";

export default class ExpenseForm extends Component {
  state = {
    amount: "",
    payee: "",
    code: "",
    memo: "",
    name: "",
    payeeId: "",
    payDate: "",
    files: [],
    projectIsOpen: false,
    projectName: "",
    tipShow: false,
    tipBoxTop: 0,
    payeeList: [],
    bankList: [], //开户行
    bankId: "",
    bankName: "",
    loading: false,
    creditCode: "",
    files2: [], //流水凭证
  };
  get navBarTitle() {
    const { router } = Taro.getCurrentInstance();
    if (router?.params.did) {
      return "支出编辑";
    }
    return "支出新增";
  }
  componentDidMount(): void {
    // this.fetchDetail();
    this.initData();
  }
  componentDidShow(){
    const {payeeId} = this.state;
    if(payeeId){
      Req.get("/config/payee/" + payeeId).then((r) => {
        this.setState({
          bankName:"",
          bankId:null,
          bankList: r.data?.bank.map((e) => ({
            displayName: `${e.name}【${e.code}】`,
            ...e,
          })),
        });
      });
    }
  } 
  initData = () => {
    const { router } = Taro.getCurrentInstance();
    if (router?.params.did) {
      Req.get(`/project/expenses/${router.params.did}`).then((r) => {
        console.log("rr", r);
        if (r.code === 200) {
          let _files = [];
          if (r.data.img) {
            _files = r.data.img.split(",").map((e) => {
              return {
                url: BASE_URL + e,
              };
            });
          }
          let _files2 = [];
          if (r.data.proofImg) {
            _files2 = r.data.proofImg.split(",").map((e) => {
              return {
                url: BASE_URL + e,
              };
            });
          }
          this.setState({
            name: r.data.payee.name,
            code: r.data.payee.code,
            payeeId: r.data.payee.id,
            amount: r.data.amount,
            memo: r.data.memo,
            payDate: r.data.payDate,
            files: _files,
            files2: _files2,
            creditCode: r.data.payee.creditCode,
          });
          if (r.data.bank && r.data.payee.id) {
            this.setState({
              bankId: r.data.bank.id,
              bankName: r.data.bank.name,
            });
            Req.get("/config/payee/" + r.data.payee.id).then((r) => {
              this.setState({
                bankList: r.data?.bank.map((e) => ({
                  displayName: `${e.name}【${e.code}】`,
                  ...e,
                })),
              });
            });
          }
        }
      });
    }
  };
  onSubmit = () => {
    const {
      amount = "",
      payeeId = "",
      code = "",
      memo = "",
      payDate,
      name = "",
      files,
      files2,
      creditCode,
      bankId,
      bankName,
    } = this.state;
    if (isEmpty(name)) {
      Taro.showToast({
        title: "供应商不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    if (isEmpty(creditCode)) {
      Taro.showToast({
        title: "信用代码不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    if (isEmpty(amount)) {
      Taro.showToast({
        title: "支出金额不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    if (files2.length === 0) {
      Taro.showToast({
        title: "流水凭证不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    if (isEmpty(payDate)) {
      Taro.showToast({
        title: "支付日期不能为空",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    const { router } = Taro.getCurrentInstance();
    if (router?.params.id) {
      uploadImgConvertUrl(files).then((results) => {
        let img = results
          .map((e: any) => {
            if (e?.data) {
              return JSON.parse(e.data)?.fileName;
            } else {
              return e.fileName;
            }
          })
          .join(",");

        uploadImgConvertUrl(files2).then((results) => {
          let proofImg = results
            .map((e: any) => {
              if (e?.data) {
                return JSON.parse(e.data)?.fileName;
              } else {
                return e.fileName;
              }
            })
            .join(",");
          if (router?.params.did) {
            Req.post("/project/expenses/edit", {
              id: router?.params.did,
              payDate,
              futuresProjectId: router.params.id,
              amount,
              name,
              payeeId,
              code,
              memo,
              img,
              proofImg,
              creditCode,
              bankId,
              bankName,
            })
              .then((r) => {
                if (r.code === 200) {
                  Taro.eventCenter.trigger("refreshData", {
                    force: true,
                    did: router.params.did,
                  });
                  Taro.navigateBack();
                  // eventCenter会重复执行多次，可能是生命周期方法的关系
                  // Taro.redirectTo({
                  //   url:`/pages/expense-management/index?id=${router.params.id}`
                  // })
                }
              })
              .catch((e) => {
                console.log(e);
              });
          } else {
            Req.post("/project/expenses/add", {
              payDate,
              futuresProjectId: router.params.id,
              amount,
              name,
              payeeId,
              code,
              memo,
              img,
              proofImg,
              creditCode,
              bankId,
              bankName,
            })
              .then((r) => {
                if (r.code === 200) {
                  Taro.eventCenter.trigger("refreshData", {
                    force: true,
                    futuresProjectId: router.params.id,
                  });
                  Taro.navigateBack();
                }
              })
              .catch((e) => {
                console.log(e);
              });
          }
        });
      });
    }
  };
  fetchDetail = () => {
    const { router } = Taro.getCurrentInstance();
    if (router?.params.id) {
      Req.get("/project/expenses/" + router.params.id)
        .then((r) => {
          if (r.code === 200) {
            const { payDate, payee, amount, memo } = r.data;
            this.setState({
              payDate,
              payee,
              amount,
              memo,
            });
          }
        })
        .catch((e) => {});
    }
  };
  onChange = (files) => {
    this.setState({
      files,
    });
  };
  onDateChange = (e) => {
    console.log(e);
    this.setState({
      payDate: e.detail.value,
    });
  };
  onChangeProjects = () => {
    this.setState({
      projectIsOpen: true,
    });
  };
  loadPayee = (name: string) => {
    const user_info = getInfo();
    const { loading } = this.state;
    if (loading) return;

    this.setState(
      {
        loading: true,
      },
      () => {
        Req.get(
          "/config/payee/list",
          {
            name,
            companyId: user_info.company?.id,
            pageNum: 1,
            pageSize: 20,
          },
          {
            loading: false,
          }
        )
          .then((r) => {
            this.setState({
              payeeList: r.rows,
              loading: false,
            });
          })
          .catch((e) => {
            this.setState({
              loading: false,
            });
          });
      }
    );
  };
  render(): ReactNode {
    const {
      payDate,
      projectIsOpen,
      tipShow,
      tipBoxTop,
      payeeList,
      loading,
      creditCode,
      bankList,
      bankId,
      bankName,
      code,
      payeeId,
    } = this.state;
    return (
      <View className="ef-container app-container">
        <AtNavBar
          leftIconType="chevron-left"
          leftText="返回"
          color="#3051BE"
          onClickLeftIcon={() => {
            Taro.navigateBack();
          }}
        >
          <View>{this.navBarTitle}</View>
        </AtNavBar>
        <AtList>
          {/* <AtListItem
            title="项目"
            className="form-list-item no-active-effect-item"
            note={
              <View>
                <Text>请选择</Text>
              </View>
            }
          /> */}
          <AtListItem
            title="供应商"
            className="form-list-item no-active-effect-item form-label-required"
            note={
              <View className="input-tip-list">
                <Input
                  id="payee-name"
                  value={this.state.name}
                  onInput={(e) => {
                    this.setState(
                      {
                        name: e.detail.value,
                      },
                      () => {
                        debounce(() => {
                          console.log("ccc");
                          this.loadPayee(e.detail.value);
                        }, 200)();
                      }
                    );
                  }}
                  onFocus={() => {
                    const query = Taro.createSelectorQuery();
                    query
                      .select("#payee-name")
                      .boundingClientRect((rect: any) => {
                        const { top, height } = rect;
                        this.setState({
                          tipShow: true,
                          tipBoxTop: top + height + 10,
                        });
                      })
                      .exec();
                  }}
                  placeholder="请输入"
                />
              </View>
            }
          />
          {/* <AtListItem
            title="供应商编码"
            className="form-list-item no-active-effect-item form-label-required"
            note={
              <View>
                <Input
                  value={this.state.code}
                  onInput={(e) => {
                    this.setState({
                      code: e.detail.value,
                    });
                  }}
                  placeholder="请输入"
                />
              </View>
            }
          /> */}
          <AtListItem
            className="form-list-item  no-arrow-space form-label-required"
            title="信用代码"
            note={
              <View className="code-search">
                <Input
                  value={creditCode}
                  onInput={(e) => {
                    this.setState({
                      creditCode: e.detail.value,
                    });
                  }}
                  placeholder="请输入"
                />
                <AtButton
                  onClick={() => {
                    Req.get("/company/tyc", {
                      creditCode,
                    })
                      .then((r) => {
                        console.log("rrr",r)

                        this.setState({
                          name: r.title,
                          bankName:"",
                          bankId:null
                        });
                          const user_info = getInfo();
                      
                        Req.get(
                          "/config/payee/list",
                          {
                            name:r.title,
                            companyId: user_info.company?.id,
                            pageNum: 1,
                            pageSize: 20,
                          }
                        )
                          .then((r) => {
                            if (r.rows && r.rows.length) {
                              const { bank, id, name } = r.rows[0];
                              this.setState({
                                payeeId:id,
                                name:name,
                                bankList:bank.map((e) => ({
                                  displayName: `${e.name}【${e.code}】`,
                                  ...e,
                                })),
                              })
                            }else{
                              this.setState({
                                bankList:[],
                                payeeId:null
                              })
                            }
                           
                          })
                      })
                      .catch((e) => {});
                  }}
                >
                  查询
                </AtButton>
              </View>
            }
          />
          {bankList.length > 0 && (
            <Picker
              mode="selector"
              range={bankList}
              rangeKey="displayName"
              onChange={(e) => {
                this.setState({
                  bankId: bankList[e.detail.value]?.id,
                  bankName: bankList[e.detail.value]?.displayName,
                });
              }}
            >
              <AtListItem
                title={"账户信息"}
                className="form-list-item  no-arrow-space"
                note={<View style={{
                  whiteSpace:'nowrap'
                }}>{isEmpty(bankName) ? "请选择" : bankName}</View>}
                extraText={
                  <View className="code-search">
                    <AtButton onClick={e => {
                      e.stopPropagation();
                      Taro.navigateTo({
                        url:`/pages/account-form/index?payeeId=${payeeId}`
                      })
                    }}>新增</AtButton>
                  </View>
                }
              />
            </Picker>
          )}

          {bankList.length === 0 && (
            <>
              <AtListItem
                title={"开户行"}
                className="form-list-item  no-arrow-space"
                note={
                  <View>
                    <Input
                      value={bankName}
                      placeholder="请输入"
                      onInput={(e) => {
                        this.setState({
                          bankName: e.detail.value,
                        });
                      }}
                    />
                  </View>
                }
              />
              <AtListItem
                title={"银行账户"}
                className="form-list-item  no-arrow-space"
                note={
                  <View>
                    <Input
                      value={code}
                      placeholder="请输入"
                      onInput={(e) => {
                        this.setState({
                          code: e.detail.value,
                        });
                      }}
                    />
                  </View>
                }
              />
            </>
          )}

          <AtListItem
            title="支出金额"
            extraText={"万元"}
            className="form-list-item no-active-effect-item form-label-required"
            note={
              <View>
                <Input
                  type="digit"
                  value={this.state.amount}
                  onInput={(e) => {
                    this.setState({
                      amount: e.detail.value,
                    });
                  }}
                  placeholder="请输入"
                />
              </View>
            }
          />
          {/* <AtListItem
            title="收款方"
            className="form-list-item no-active-effect-item"
            note={
              <View>
                <Input 
                
                placeholder="请输入" />
              </View>
            }
          /> */}
          <AtListItem
            title="流水凭证"
            className="form-list-item form-label-required"
            note={
              <View className="liushui-box">
                <AtImagePicker
                  length={1}
                  files={this.state.files2}
                  onChange={(files) => {
                    this.setState({
                      files2: files,
                    });
                  }}
                />
              </View>
            }
          />
          <Picker value={payDate} mode="date" onChange={this.onDateChange}>
            <AtListItem
              className="form-list-item form-label-required"
              arrow="down"
              note={
                <View>
                  <Text>{isEmpty(payDate) ? "请选择" : payDate}</Text>
                </View>
              }
              title="支付日期"
            />
          </Picker>
          <AtListItem
            title="备注"
            className="form-list-item no-active-effect-item remark-form-item no-arrow-space"
            note={
              <View>
                <Textarea
                  value={this.state.memo}
                  onInput={(e) => {
                    this.setState({
                      memo: e.detail.value,
                    });
                  }}
                  className="remark-textarea"
                  placeholder="请输入文字"
                />
              </View>
            }
            extraText={
              <View className="img-picker">
                <AtImagePicker
                  length={1}
                  files={this.state.files}
                  onChange={this.onChange}
                />
              </View>
            }
          />
        </AtList>
        <AtButton
          className="bottom-btn primary-btn-color"
          onClick={this.onSubmit}
          circle
          type="primary"
        >
          提交
        </AtButton>

        <ProjectSelect
          visible={projectIsOpen}
          onClose={() => {
            this.setState({
              projectIsOpen: false,
            });
          }}
          onSelect={() => {}}
        />
        {tipShow && (
          <View
            className={`input-tip-list-box fade-box
              ${tipShow ? "fade-in" : "fade-out"}
            `}
            style={{
              top: tipBoxTop + "px",
            }}
          >
            <ScrollView className="scrollView_payeee" scrollY>
              {payeeList.map((e: any, i) => (
                <View
                  key={i}
                  onClick={() => {
                    this.setState({
                      payeeId: e.id,
                      name: e.name,
                      code: e.code,
                      creditCode: e.creditCode,
                      bankList: e?.bank ?? [],
                      tipShow: false,

                      bankName:"",
                      bankId:null,
                    });
                  }}
                  hoverClass="hover-tab-btn"
                  className="payee-item"
                >
                  <Text>{e.name}</Text>
                </View>
              ))}
            </ScrollView>
          </View>
        )}
      </View>
    );
  }
}
